package com.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Auther: tong
 * @Date: 2023/01/18/23:39
 * @Description:
 */
@Component
public class MyAspect {

    @Pointcut("execution(* com.example.service..*.*(..))")
    public void servicePointCut() {
    }

    public void before(JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();

        System.out.println("方法所在的全类名是:"+signature.getDeclaringTypeName());
        System.out.println("方法名称是:"+signature.getName());
        System.out.println("方法参数是:"+ Arrays.toString(point.getArgs()));
    }

    public void after(JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();

        System.out.println("方法所在的全类名是:"+signature.getDeclaringTypeName());
        System.out.println("方法名称是:"+signature.getName());
        System.out.println("方法参数是:"+ Arrays.toString(point.getArgs()));
    }

    public void afterReturning(JoinPoint point,Object result){
        MethodSignature signature = (MethodSignature) point.getSignature();

        System.out.println("方法所在的全类名是:"+signature.getDeclaringTypeName());
        System.out.println("方法名称是:"+signature.getName());
        System.out.println("方法参数是:"+ Arrays.toString(point.getArgs()));
        System.out.println("result:"+result);
    }

    public void afterThrowing(JoinPoint point,Throwable throwable){
        System.out.println("方法的异常对象是:"+throwable);
    }

    public Object around(ProceedingJoinPoint point) {
        // 方法调用时传入的参数
        Object[] args = point.getArgs();
        // 被代理对象
        Object target = point.getTarget();
        // 获取被增强方法签名封装的对象
        MethodSignature signature = (MethodSignature) point.getSignature();
        Object proceed = null;
        try {
            proceed = point.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return proceed;
    }
}
